package commands;

import java.util.ArrayList;

import properties.Properties;

import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.internal.org.json.*;

/**
 * This class represents the Command getTwitter
 * 
 * @author Mark Visscher
 * @version 1.0
 * 
 */
public class GetTwitterQueryCommand implements Command {

	private JSONObject jObject;

	public GetTwitterQueryCommand(JSONObject jObject) {
		this.jObject = jObject;
	}

	@Override
	public String execute() throws JSONException {
		JSONArray sendArray = new JSONArray();

		JSONArray parameters = jObject.getJSONArray("getTwitterQuery");
		ArrayList<String> keywords = functions.StaticFunctions
				.JSONArrayToArrayList(parameters);

		int maxTweets = jObject.getInt("maxTweets");
		if (maxTweets > 1500)
			maxTweets = 1500;

		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true);
		cb.setOAuthConsumerKey(Properties.getProperties().getConsumerKey());
		cb.setOAuthConsumerSecret(Properties.getProperties()
				.getConsumerSecret());
		cb.setOAuthAccessToken(Properties.getProperties().getAccessToken());
		cb.setOAuthAccessTokenSecret(Properties.getProperties()
				.getAccessTokenSecret());

		TwitterFactory tf = new TwitterFactory(cb.build());
		Twitter myTwitter = tf.getInstance();
		try {
			String queryWords = "";
			for (String keyword : keywords) {
				queryWords += keyword + " ";
			}
			Query query = new Query(queryWords);
			query.setRpp(maxTweets);
			QueryResult qr = myTwitter.search(query);

			ArrayList<Tweet> tweets = (ArrayList<Tweet>) qr.getTweets();
			for (Tweet t : tweets) {
				JSONObject jOwner = new JSONObject();
				JSONObject jMessage = new JSONObject();

				jOwner.put("twitter_id", t.getFromUserId());
				jOwner.put("name", t.getFromUser());
				jOwner.put("profile_image_url", t.getProfileImageUrl());

				jMessage.put("text", t.getText());
				jMessage.put("created_at", t.getCreatedAt());
				if (t.getPlace() != null)
					jMessage.put("place", t.getPlace().getName());
				jMessage.put("owner", jOwner);
				jMessage.put("tweet_id", t.getId());

				sendArray.put(jMessage);
			}
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		return sendArray.toString();
	}
}
